#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
class Sock
{
public:
    Sock(uint16_t port = 8080, std::string ip = "0.0.0.0")
        : _port(port), _ip(ip)
    {
    }
    int SockCreate()
    {
        _sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_sock < 0)
        {
            std::cout << "socket fail..." << std::endl;
            exit(1);
        }
        return _sock;
    }
    void Bind()
    {
        sockaddr_in serve;
        memset(&serve, 0, sizeof(serve));
        serve.sin_addr.s_addr = inet_addr(_ip.c_str());
        serve.sin_port = htons(_port);
        serve.sin_family = AF_INET;
        socklen_t len = sizeof(serve);
        int ret = bind(_sock, (sockaddr *)(&serve), len);
        if (ret < 0)
        {
            std::cout << "Bind fail..." << std::endl;
            exit(2);
        }
    }
    void Listen()
    {
        int ret = listen(_sock, 20);
        if (ret < 0)
        {
            std::cout << "Listen fail..." << std::endl;
            exit(3);
        }
    }
    void Connect(int sock, std::string ip, uint16_t port)
    {
        sockaddr_in serve;
        memset(&serve, 0, sizeof(serve));
        serve.sin_addr.s_addr = inet_addr(ip.c_str());
        serve.sin_family = AF_INET;
        serve.sin_port = htons(port);
        int ret = connect(sock, (sockaddr *)(&serve), sizeof(serve));
        if (ret < 0)
        {
            std::cout << "Connect fail..." << std::endl;
            exit(4);
        }
    }
    int Accept()
    {
        int sock = 0;
        sockaddr_in client;
        socklen_t len = sizeof(client);
        sock = accept(_sock, (sockaddr *)(&client), &len);
        if (sock < 0)
        {
            std::cout << "Accept fail..." << std::endl;
            exit(5);
        }
        return sock;
    }
    ~Sock()
    {
        if(_sock > 0)
            close(_sock);
    }
private:
    int _sock;
    uint16_t _port;
    std::string _ip;
};